package com.server.service.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.server.password.MyMD5;
import com.server.service.ICommonDataService;
import com.server.service.IRewardConfigService;
import com.server.service.ISourceService;
import com.server.service.IUserConfigService;
import com.server.web.DataVector;
import com.server.web.RequestInput;

@Service("SourceService")
public class SourceService implements ISourceService {

	private static final String TABLE_NAME = "reward.source";
	private static final String TABLE_NAME_TYPE = "reward.source_type";

	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private ICommonDataService commonDataService;
	@Autowired
	private IRewardConfigService rewardConfig;
	@Autowired
	private IUserConfigService userConfigService;

	@Override
	public Boolean addType(Integer typeNo, String type, String note) {
		if (typeNo == null) {
			typeNo = 0;
		}
		if (note == null) {
			note = "无";
		}
		String sql = "insert into %s (TypeNo,SourceType,Note) values (%s,'%s','%s')";
		return jdbcTemplate.update(String.format(sql, TABLE_NAME_TYPE, typeNo,
				type, note)) > 0;
	}

	@Override
	public Boolean updateType(Integer typeNo, String type, String note,
			Integer id) {
		String sql = "update %s set TypeNo=%s,SourceType='%s',Note='%s' where Id=%s";
		return jdbcTemplate.update(String.format(sql, TABLE_NAME_TYPE, typeNo,
				type, note, id)) > 0;
	}

	@Override
	public Boolean deleteType(String ids) {
		String sql = "delete from %s where Id in (%s)";
		return jdbcTemplate.update(String.format(sql, TABLE_NAME_TYPE, ids)) > 0;
	}

	@Override
	public List<Map<String, Object>> getTypeList(RequestInput requestInput) {
		DataVector<Map<String, Object>> listData = commonDataService
				.getListData(TABLE_NAME_TYPE, "Valid=1", "Id asc", requestInput);
		return listData.getList();
	}

	@Override
	public Map<String, Object> getTypeForm(Integer id) {
		return commonDataService.getFormData(TABLE_NAME_TYPE, "Id",
				id.toString(), null, null);
	}

	/**
	 * 来源添加
	 * @param operator
	 * @param inputMap
	 * @return
	 * @author ServerZhang
	 * @date 2017年3月30日
	 */
	@Override
	public Boolean add(String operator, Map<String, Object> inputMap) {
		String cardObj = inputMap.get("CardID").toString();
		String phoneObj = inputMap.get("PhoneNo").toString();
		if (StringUtils.isEmpty(phoneObj)) {
			return false;
		}
		if (StringUtils.isEmpty(cardObj)) {
			inputMap.put("CardID", phoneRandToCardId(phoneObj));
		}
		inputMap.put("Password", MyMD5.circularlyEncrypt("123456", 3));
		String phoneNo = inputMap.get("PhoneNo").toString();
		String cardId = inputMap.get("CardID").toString();
		// 查询是否可添加
		Boolean checkUser1 = this.checkUserByPhone(phoneNo);
		Boolean checkUser2 = this.checkUser(cardId);
		return checkUser1 && checkUser2 
				&& commonDataService.add(operator, TABLE_NAME, inputMap);
	}
	public Object phoneRandToCardId(String phoneStr){
		String provinces[] = { "11", "12", "13", "14", "15", "21", "22", "23",
				"31", "32", "33", "34", "35", "36", "37", "41", "42", "43",
				"44", "45", "46", "50", "51", "52", "53", "54", "61", "62",
				"63", "64", "65", "71", "81", "82" };
		String randStr1 = provinces[new Random().nextInt(provinces.length - 1)];
		String phoneStr1 = phoneStr.substring(0, 2);
		String countys[] = { "01", "02", "03", "04", "05", "06", "07", "08",
				"09", "10", "21", "22", "23", "24", "25", "26", "27", "28",
				"29", "30", "31", "32", "33", "34", "35", "36", "37", "38" };
		String randStr2 = countys[new Random().nextInt(countys.length - 1)];
		String phoneStr2 = phoneStr.substring(2, 5);
		String checks[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
		String randStr3 = checks[new Random().nextInt(checks.length - 1)];
		String phoneStr3 = phoneStr.substring(5, 8);
		String randStr4 = checks[new Random().nextInt(checks.length - 1)];
		String phoneStr4 = phoneStr.substring(8, 11);
		String randStr5 = checks[new Random().nextInt(checks.length - 1)];
		Object randCardId = randStr1+phoneStr1+randStr2+phoneStr2+randStr3+phoneStr3+randStr4+phoneStr4+randStr5;
		return randCardId;
	}
	@Override
	public Boolean add(String operator, Integer typeId, String cardIds) {
		String userSql = "SELECT LoginName,PhoneNo,Email,`Password`,UserName,Sex,CardID,CardA,CardB,UserPhoto,UserIco,AlipayNo,WechatNo,BankNo,BirthDay,Residence,Province,Registry,City,Area FROM reward.user where CardID in ('%s')";
		List<Map<String, Object>> userList = jdbcTemplate.queryForList(String.format(userSql, cardIds.replaceAll(",", "','")));
		Iterator<Map<String, Object>> iterator = userList.iterator();
		while(iterator.hasNext()){
			Map<String, Object> next = iterator.next();
			next.put("SourceTypeId", typeId);
		}
		return commonDataService.addBatch(operator, TABLE_NAME, userList);
	}
	public Boolean checkUser(String cardId) {
		if (StringUtils.isEmpty(cardId)) {
			return false;
		}
		String sql = "select count(CardID) from %s where CardID='%s'";
		return jdbcTemplate.queryForObject(
				String.format(sql, TABLE_NAME, cardId), Integer.class) < 1;
	}
	public Boolean checkUserByPhone(String phone) {
		if (StringUtils.isEmpty(phone)) {
			return false;
		}
		String sql = "select count(PhoneNo) from %s where PhoneNo='%s'";
		return jdbcTemplate.queryForObject(
				String.format(sql, TABLE_NAME, phone), Integer.class) < 1;
	}
	@Override
	public Boolean update(String operator, Map<String, Object> inputMap) {
		Object cardObj = inputMap.get("CardID");
		if (cardObj == null) {
			return false;
		}
		String cardId = cardObj.toString();
		return commonDataService.update(operator, TABLE_NAME, "CardID", cardId,
				inputMap);
	}
	@Override
	public Map<String, Object> delete(String cardIds){
		Boolean isSuccess = false;
		Integer errorCount = 0;
		Map<String, Object> returnMap = new HashMap<String, Object>();
		if (!StringUtils.isEmpty(cardIds)) {
			int tCount = cardIds.split(",").length;
			StringBuffer sqlBuffer = new StringBuffer();
			sqlBuffer.append("delete from ").append(TABLE_NAME).append(" where CardID in('")
			.append(cardIds.replaceAll(",", "','")).append("')");
			int uCount = jdbcTemplate.update(sqlBuffer.toString());
			if((errorCount = tCount - uCount) == 0){
				isSuccess = true;
			}
		}
		returnMap.put("isSuccess", isSuccess);
		returnMap.put("errorCount", errorCount);
		return returnMap;
	}
	@Override
	public DataVector<Map<String, Object>> getList(RequestInput requestInput,
			Integer typeId){
		String _whereStr = null;
		if (typeId != null && !typeId.equals(0)) {
			_whereStr = "SourceTypeId="+typeId;
		}
		return commonDataService.getListData(TABLE_NAME, _whereStr, "CreateTime desc", requestInput);
	}
	@Override
	public Map<String, Object> getForm(String cardId){
		return commonDataService.getFormData(TABLE_NAME, "CardID", cardId, null, null);
	}
	
	@Override
	public Map<String, Object> getFormByPhone(String phone){
		return commonDataService.getFormData(TABLE_NAME, "PhoneNo", phone, null, null);
	}

}
